import json
import logging
import random
import string

from aliyunsdkcore.client import AcsClient


class AliBase(object):
    def __init__(self, ak='LTAI5t8hMg636oPimZoqYnbM', sk='ltYzWTvXBVaoqcgZVHJb2uZ4CHeKmy',
                 region='cn-beijing'):
        self.ak = ak
        self.sk = sk
        self.region = region
        self.client = AcsClient(ak, sk, region)

    def base(self, model, **kwargs):
        request = model()
        request.set_accept_format('json')
        # 通过for循环将查询参数添加到请求里面
        # request.set_InstanceId("xxxxx")
        for k, v in kwargs.items():
            request.add_query_param(k, v)
        try:
            response = self.client.do_action_with_exception(request)
            # response是bytes类型，通过decode解码为str。
            # json.loads将字符串反序列化为python对象便于处理
            response = json.loads(response.decode('utf-8'))
        except Exception as e:
            logging.error(f'执行失败，原因是：{str(e)}')
            response = {}
        return response

    @property
    def generate_password(self):
        length = 8
        strings = string.digits + string.ascii_letters
        return "".join(random.sample(strings, length - 1)) + random.choice(string.punctuation)
